from django.shortcuts import render
from django.views.generic.base import View
from mangguo_pro.apps.newsapp.models import NewsChannel,Article
from django import http
from django.core.paginator import Paginator, EmptyPage

# Create your views here.
class  IndexView(View):
    def get(self,request,channel_id=1,page_num=1):
        try:
            #获取NewChannel对象
            channel=NewsChannel.objects.get(id=channel_id)
            print(channel)
            print(type(channel))
        except:
            return http.HttpResponseNotFound('未找到channel_id')

        else:
            #获取当前频道下的所有类别id
            category_id_list=[category.id   for category in channel.newscategory_set.all() if category]
            print(category_id_list)
        articles=Article.objects.filter(category_id__in=category_id_list).order_by('id')
        print(articles)
        #创建分页器，每页N条记录
        paginator=Paginator(articles,5)
        try:
            page_article=paginator.page(page_num)
        except:
            return http.HttpResponseNotFound('没有发现page_article')

        return render(request,'newsapp/index.html',{'articles':page_article,'channel_id':channel_id})

class Display(View):
    def get(sel,request):
        return  render(request,'newsapp/practice.html')


class DetailView(View):
    def get(self,request,article_id):
        try:
            article=Article.objects.get(id=article_id)
        except:
            return http.HttpResponseNotFound('未找到article')

        return render(request,'newsapp/detail.html',{"article":article})
